# -*- coding:utf-8 -*-
import configparser
import os
import random
import re
import sys
import time
from concurrent import futures
from urllib.parse import urlencode
# /e/member/login/
# 测试是否开通空间
# /e/member/mspace/index.php
import requests

# 或当exe文件运行目录的路径
def getRealPath(name):
    config_name = name
    application_path = ''
    # determine if application is a script file or frozen exe
    if getattr(sys, 'frozen', False):
        application_path = os.path.dirname(sys.executable)
    elif __file__:
        application_path = os.path.dirname(__file__)

    config_path = os.path.join(application_path, config_name)
    print(config_path)
    return config_path

#读取链接库的链接,随机选出一条
def readlinks():  #返回列表
    try:
        wordlist = []
        for line in open("links.txt", encoding='utf-8'):
            wordlist.append(line.strip())
        # print(wordlist)
        link = random.choice(wordlist)
        return link
    except:
        return 'http://www.sogou.com'
#把发帖链接写入文档
def writelinktxt(msg):
    try:
        with open('links.txt', 'a+', encoding='utf-8') as f:
            f.write(msg + '\n')
    except:
        pass

def writelogtxt(msg):
    try:
        with open('log.txt', 'a+', encoding='utf-8') as f:
            f.write(msg + '\n')
    except:
        pass
#读取配置文档
def read_ini():
    #关键词随机函数
    # 返回随机一个关键词，从keywords.txt

    #格式化关键词，把字符串里边的函数对应出来
    #{关键词}----------getkeyword()
    #{结尾词}----------getbackword()
    def format_str(str):
        str = str.replace('{关键词}','{getkeyword()}').replace('{结尾词}','{getbackword()}').replace('{微信号}','{getweixin()}')
        return str


    class postinfo:
        easyhost=''
        host=''
        allhost=''
        username=''
        password=''
        runnum=''
        email=''
        weixin=''
        title=''
        content=''
        info=''
    #获取当前目录路径
    config_name = getRealPath('WebConfig.ini')

    print(config_name)

    config = configparser.ConfigParser()
    config.read(config_name,encoding='utf-8-sig')  #获取配置文件的的绝对路径
    postinfo.easyhost = config.get("SETINI", "easyhost")
    postinfo.host = config.get("SETINI", "host")
    postinfo.allhost = config.get("SETINI", "allhost")
    postinfo.username = config.get("SETINI", "username")
    postinfo.password = config.get("SETINI", "password")
    postinfo.email = config.get("SETINI", "email")
    postinfo.runnum = config.get("SETINI", "runnum")
    postinfo.weixin = config.get("SETINI", "weixin")
    postinfo.title = config.get("SETINI", "title")
    postinfo.content = config.get("SETINI", "content")
    postinfo.info = config.get("SETINI", "info")
    postinfo.title =format_str(postinfo.title)
    postinfo.content =format_str(postinfo.content)
    postinfo.info =format_str(postinfo.info)



    # eval---指定函数1
    def getkeyword():
        wordlist = []
        for line in open("keywords.txt", encoding='utf-8'):
            wordlist.append(line.strip())
        keyword = random.choice(wordlist)
        # print(a)  # print(wordlist)
        return keyword

    # 结尾词随机函数        # eval---指定函数2
    def getbackword():
        wordlist = []
        for line in open("backwords.txt", encoding='utf-8'):
            wordlist.append(line.strip())
        backword = random.choice(wordlist)
        # print(a)  # print(wordlist)
        return backword
    # eval---指定函数3
    def getweixin():
        return postinfo.weixin
    postinfo.title = eval(postinfo.title)
    postinfo.content = eval(postinfo.content)
    postinfo.info = eval(postinfo.info)
    # print('-----------1-------------------')
    #
    # print(postinfo.title)
    # print(postinfo.content)
    # print(postinfo.info)
    # print('-----------1-------------------')

    return postinfo
    # try:
    #
    # except Exception as e:
    #     print("错误提示1：Section 'SET' NOT exists")
    #     print('错误提示2：把ini里边不能出现多余的大括号，一个也不能')
    #     return None
def writetxt(msg):
    try:
        with open('links1.txt', 'a+', encoding='utf-8') as f:
            f.write(msg + '\n')
    except:
        pass
class myrequest:
    def __init__(self,easyhost,host,allhost,username,password,email,title,content,userinfo,i):

        print(f'i程序{i}初始化运行')
        print(time.strftime('%Y-%m-%d %H:%M:%S'))
        self.easyhost = easyhost
        self.host = host
        self.allhost = allhost
        self.username = username
        self.password = password
        self.email = email
        self.title = title
        self.content = content
        self.userinfo = userinfo
        self.i = i
        # print('-----------2-------------------')
        # print(self.title)
        # print(self.content)
        # print(self.userinfo)
        # print('-----------2-----------------------')

        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
            'Accept-Encoding': 'gzip',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'max-age=0',
            'Host': self.host,
            'X-Real-IP': '225.58.45.24',
            'X-Forwarded-For': '8.8.8.8',
            'Connection': 'keep-alive'
        }
        session = requests.Session()
        session.headers = headers
        self.session = session
        self.i = i


    # POST注册函数
    def zhuCe(self):
        postData = {
            'enews': 'register',
            'groupid': '1',
            'tobind': '0',
            'username': self.username,
            'password': self.password,
            'repassword': self.password,
            'email': self.email,
            'truename': '',
            'oicq': '',
            'msn': '',
            'mycall': '',
            'phone': '',
            'homepage': '',
            'userpicfile': '(binary)',
            'address': '',
            'zip': '',
            'saytext': self.userinfo,
            'Submit': '(unable to decode value)'
        }

        html = self.session.post(url=f'{self.allhost}/e/member/doaction.php', data=postData, verify=False, timeout=125)
        print(f'Runapp{self.i}号--注册完成，用户名是{self.username},密码是{self.password}')
        print(html.text)


    #POST发帖发帖函数
    def faTie(self):
        # 2----------Post发帖,公告模块
        datas = {
            'spacename': self.title,
            'spacegg': f'{self.content}   {readlinks()}    {readlinks()}  {readlinks()}',
            'Submit': '(unable to decode value)',
            'enews': 'DoSetSpace'
        }
        # 将form提交数据转换成网页对应合适，本网站的格式gb2312，然后不要用datas直接放到会话请求里边，用转换好的格式data_gb2312来请求
        # data_UTF8 = urlencode(datas, encoding='utf-8')
        html = self.session.post(url=f'{self.allhost}/e/member/mspace/index.php', data=datas,verify=False, timeout=125)
        print(html.text)
        # print(self.session.cookies.get_dict())
        dictstr  = str(self.session.cookies.get_dict())
        idmatch = re.compile(fr"'[\S]+userid': '([\S]+)'")
        myvalue = re.findall(idmatch, dictstr)
        userid = myvalue[0]
        # 用户的id号码是

        writelinktxt(f'{self.allhost}/e/space/?userid={userid}')
        nowtimt = time.strftime('%Y-%m-%d %H:%M:%S')
        writelogtxt(f"['{self.username}','{self.password}','{nowtimt}']")
        # self.session.close()
        print(f'Runapp{self.i}号--发帖完成，用户名是{self.username},密码是{self.password}')
        # print(html.text)

    #POST登录函数
    def login(self):
        postData = {
            'ecmsfrom': '',
            'enews': 'login',
            'tobind': '0',
            'username': self.username,
            'password': self.password,
            'lifetime': '99990',
            'Submit': '(unable to decode value)'}
        # data_UTF8 = urlencode(postData, encoding='utf-8')
        html = self.session.post(url=f'{self.allhost}/e/member/doaction.php', data=postData, verify=False,timeout=125)
        # print(self.session.cookies.get_dict())
        print(f'Runapp{self.i}号--登录完成，用户名是{self.username},密码是{self.password}')
        print(html.text)



    #获取GET用户信息
    def getID(self):
        html = self.session.get(url=f'{self.allhost}/e/member/EditInfo', verify=False)
        print(f'Runapp{self.i}号--获取用户信息，用户名是{self.username},密码是{self.password}')
        print(html.text)


    # GET退出函数
    def logOut(self):
        # print(123)
        html = self.session.get(url=f'{self.allhost}/e/member/doaction.php?enews=exit', verify=False)
        print(f'Runapp{self.i}号--结束运行，用户名是{self.username},密码是{self.password}')
        print(html.text)
        self.session.close()


    # 运行函数
def runweb(useinfo,i):
    print(print(useinfo.title))
    onerequest = myrequest(useinfo.easyhost,useinfo.host,useinfo.allhost,f'{useinfo.username}{i}',f'{useinfo.password}',f'{useinfo.email}{i}@163.com',useinfo.title,useinfo.content,useinfo.info,i)
    time.sleep(5)
    onerequest.zhuCe()
    time.sleep(5)
    onerequest.login()
    time.sleep(5)
    onerequest.faTie()
    time.sleep(5)
    onerequest.getID()
    time.sleep(5)
    onerequest.logOut()

    #多线程运行
def ThreadLine():
    with futures.ThreadPoolExecutor(max_workers=50) as executor:  # 多线程
        useinfo = read_ini()
        for i in range(int(useinfo.runnum)):
            #在循环内实例化，在外边实例化会让所有的值一致
            useinfo = read_ini()
            executor.submit(runweb,useinfo,i)
if __name__ == '__main__':
    ThreadLine()



